//
//  DemoView.m
//  mendianjieke
//
//  Created by 响当当 on 11/16/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "DemoView.h"
#import "LoginFailedView.h"

@interface DemoView()<UITextFieldDelegate>
{
    
    dispatch_source_t _timer;
    
}
@property (nonatomic, strong)UIButton *areaButton;//区号
@property (nonatomic, strong)UITextField *phoneTextField;//手机号输入
@property (nonatomic, strong)UITextField *codeTextFiedld;//密码登录
@property (nonatomic, strong)UIButton *sendMessageButton;//发送短信验证码

@property (nonatomic, strong)NSString *phoneNum;
@property (nonatomic, strong)NSString *codeNum;

@property (nonatomic, strong)LoginFailedView *loginFailedView;//提示
@property (nonatomic, strong)UIView *footView;//
@property (nonatomic, strong)UIButton *loginButton;//登录
@end

@implementation DemoView

- (LoginFailedView *)loginFailedView
{
    if (!_loginFailedView)
    {
        _loginFailedView = [[LoginFailedView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT)];
    }
    return _loginFailedView;
}


- (UIButton *)areaButton
{
    if (!_areaButton)
    {
        _areaButton = [Utilties creatButtonWithFrame:CGRectMake(30*kUIScaleBasePlus,0,28*kUIScaleBasePlus,25*kUIScaleBasePlus)
                                        textAligment:UIControlContentHorizontalAlignmentCenter
                                                text:@"+86"
                                            textClor:LCHexColor(0x282828)
                                           buttonBGC:[UIColor clearColor]
                                            textFont:13*kUIScaleBasePlus
                                              target:self
                                              method:@selector(areaButtonClcik)];
        
        
        UIImageView *rowImageView = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_areaButton.frame)+7*kUIScaleBasePlus,8*kUIScaleBasePlus,6*kUIScaleBasePlus,10*kUIScaleBasePlus)];
        rowImageView.image = [UIImage imageNamed:@"maihu_xiangyou"];
        [self addSubview:rowImageView];
    }
    return _areaButton;
}


- (UITextField *)phoneTextField
{
    if (!_phoneTextField)
    {
        _phoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.areaButton.frame)+30*kUIScaleBasePlus,self.areaButton.frame.origin.y,200*kUIScaleBasePlus,25*kUIScaleBasePlus)];
        _phoneTextField.delegate = self;
        _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        _phoneTextField.placeholder = @"请输入手机号码";
        [_phoneTextField becomeFirstResponder];
        [_phoneTextField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventAllEvents];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(30*kUIScaleBasePlus,CGRectGetMaxY(_phoneTextField.frame)+15*kUIScaleBasePlus,315*kUIScaleBasePlus,1*kUIScaleBasePlus)];
        lineView.backgroundColor = JSALineColor;
        [self addSubview:lineView];
    }
    return _phoneTextField;
}

- (UITextField *)codeTextFiedld
{
    if (!_codeTextFiedld)
    {
        _codeTextFiedld = [[UITextField alloc]initWithFrame:CGRectMake(30*kUIScaleBasePlus,CGRectGetMaxY(self.phoneTextField.frame)+35*kUIScaleBasePlus,200*kUIScaleBasePlus,18.5*kUIScaleBasePlus)];
        _codeTextFiedld.delegate = self;
        _codeTextFiedld.keyboardType = UIKeyboardTypeNumberPad;
        _codeTextFiedld.placeholder = @"请输入验证码";
        [_codeTextFiedld addTarget:self action:@selector(codeChange:) forControlEvents:UIControlEventAllEvents];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(30*kUIScaleBasePlus,CGRectGetMaxY(_codeTextFiedld.frame)+15*kUIScaleBasePlus,315*kUIScaleBasePlus,1*kUIScaleBasePlus)];
        lineView.backgroundColor = JSALineColor;
        [self addSubview:lineView];
    }
    return _codeTextFiedld;
}

- (UIButton *)sendMessageButton
{
    if (!_sendMessageButton)
    {
        _sendMessageButton = [Utilties creatButtonWithFrame:CGRectMake(SCREEN_WIDTH-30*kUIScaleBasePlus-100*kUIScaleBasePlus,CGRectGetMaxY(self.phoneTextField.frame)+32*kUIScaleBasePlus,100*kUIScaleBasePlus,28*kUIScaleBasePlus) textAligment:UIControlContentHorizontalAlignmentCenter text:@"发送验证码" textClor:LCHexColor(0xFF7A17) buttonBGC:[UIColor clearColor] textFont:12*kUIScaleBasePlus target:self method:@selector(sendMessage:)];
        _sendMessageButton.layer.masksToBounds = YES;
        _sendMessageButton.layer.cornerRadius = _sendMessageButton.frame.size.height/2;
        _sendMessageButton.layer.borderWidth = 1;
        _sendMessageButton.layer.borderColor = LCHexColor(0xFF7A17).CGColor;
        
    }
    return _sendMessageButton;
}

- (UIView *)footView
{
    if (!_footView)
    {
        _footView = [[UIView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(self.sendMessageButton.frame)+38.5*kUIScaleBasePlus,SCREEN_WIDTH,20*kUIScaleBasePlus)];
        _footView.backgroundColor = [UIColor clearColor];
        
        
       UIButton *chooseButton = [Utilties creatButtonWithFrame:CGRectMake(30*kUIScaleBasePlus,0,14*kUIScaleBasePlus,14*kUIScaleBasePlus)
                                                   textAligment:UIControlContentHorizontalAlignmentCenter
                                                           text:@""
                                                       textClor:LCHexColor(0xFFFFFF)
                                                      buttonBGC:[UIColor clearColor]
                                                       textFont:10*kUIScaleBasePlus
                                                         target:self
                                                         method:@selector(choosClick:)];
        chooseButton.selected = YES;
        [chooseButton setImage:[UIImage imageNamed:@"yixuan"] forState:UIControlStateSelected];
        [chooseButton setImage:[UIImage imageNamed:@"weixuan"] forState:UIControlStateNormal];
        [_footView addSubview:chooseButton];
        
        UILabel *subTitleLabel = [Utilties creatLabelWithFrame:CGRectMake(CGRectGetMaxX(chooseButton.frame)+5*kUIScaleBasePlus,0,70*kUIScaleBasePlus,14*kUIScaleBasePlus)
                                                  textAligment:NSTextAlignmentLeft
                                                      textClor:LCHexColor(0x8B8B8B)
                                                      textFont:10*kUIScaleBasePlus];
        subTitleLabel.text = @"已阅读并同意";
        [_footView addSubview:subTitleLabel];
        
        UIButton *customerCodingBtn = [Utilties creatButtonWithFrame:CGRectMake(CGRectGetMaxX(subTitleLabel.frame),-5*kUIScaleBasePlus,100*kUIScaleBasePlus,14*kUIScaleBasePlus)
                                                        textAligment:UIControlContentHorizontalAlignmentLeft
                                                                text:@"《用户协议》"
                                                            textClor:LCHexColor(0xFF7A17)
                                                           buttonBGC:[UIColor clearColor]
                                                            textFont:10*kUIScaleBasePlus
                                                              target:self
                                                              method:@selector(customerClick)];
        [_footView addSubview:customerCodingBtn];
        [customerCodingBtn sizeToFit];
        
        UIButton *secretBtn = [Utilties creatButtonWithFrame:CGRectMake(CGRectGetMaxX(customerCodingBtn.frame),-5*kUIScaleBasePlus,110*kUIScaleBasePlus,14*kUIScaleBasePlus)
                                                        textAligment:UIControlContentHorizontalAlignmentLeft
                                                                text:@"《用户隐私政策》"
                                                            textClor:LCHexColor(0xFF7A17)
                                                           buttonBGC:[UIColor clearColor]
                                                            textFont:10*kUIScaleBasePlus
                                                              target:self
                                                              method:@selector(secretClick)];
        [_footView addSubview:secretBtn];
        [secretBtn sizeToFit];
    }
    return _footView;
}


- (UIButton *)loginButton
{
    if (!_loginButton)
    {
        _loginButton = [Utilties creatButtonWithFrame:CGRectMake(30*kUIScaleBasePlus,CGRectGetMaxY(self.footView.frame)+40*kUIScaleBasePlus,315*kUIScaleBasePlus,40*kUIScaleBasePlus)
                                            textAligment:UIControlContentHorizontalAlignmentCenter
                                                    text:@"登录"
                                                textClor:LCHexColor(0xFFFFFF)
                                               buttonBGC:LCHexColor(0xFF7A17)
                                                textFont:17*kUIScaleBasePlus
                                                  target:self
                                                  method:@selector(cipherLogin)];
        _loginButton.layer.masksToBounds = YES;
        _loginButton.layer.cornerRadius = _loginButton.frame.size.height/2;
        
    }
    return _loginButton;
}



- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self addSubview:self.areaButton];
        [self addSubview:self.phoneTextField];
        [self addSubview:self.codeTextFiedld];
        [self addSubview:self.sendMessageButton];
        [self addSubview:self.footView];
        [self addSubview:self.loginButton];
    }
    return self;
}

#pragma mark - Method
- (void)areaButtonClcik
{
    
}

- (void)choosClick:(UIButton *)sender
{
    if (sender.selected)
    {
        sender.selected = NO;
        self.loginButton.enabled = NO;
        [self.loginButton setBackgroundColor:LCHexColor(0xFFBA87)];
    }
    else
    {
        sender.selected = YES;
        self.loginButton.enabled = YES;
        [self.loginButton setBackgroundColor:LCHexColor(0xFF7A17)];
    }
}

/**
 *  用户协议
*/
- (void)customerClick
{
    [Utilties pushWebWithUrl:@"http://file.bztmar.com/agreement/userAgreement.html" title:@"用户协议" toUrl:nil toId:nil];

}

/**
 *  用户隐私政策
*/
- (void)secretClick
{
    [Utilties pushWebWithUrl:@"http://file.bztmar.com/agreement/privacyPolicy.html" title:@"用户隐私政策" toUrl:nil toId:nil];
}

/**
 *  手机号码
*/
- (void)textChange:(UITextField *)sender
{
    self.phoneNum = sender.text;
}

/**
 *  密码输入
*/
- (void)codeChange:(UITextField *)sender
{
    self.codeNum = sender.text;
}

/**
 *  发送验证码
*/
- (void)sendMessage:(UIButton *)sender
{
    
    [self getMessage];
    
}

//获取短信验证码
- (void)getMessage
{
    
    if (![Utilties checkTel:self.phoneTextField.text])
    {
        [SVProgressHUD showWithStatus:@"请输入正确的手机号码"];
        return;
    }
    
    WeakSelf(self)
       [infoManager getDemoCodeWithPhone:self.phoneNum
                              Sucess:^(id  _Nonnull acceptData) {
                                  NSNumber *code = acceptData[@"code"];
                                  if (code.integerValue == 400)
                                  {
                                      LoginModel *model = [[LoginModel alloc]init];
                                      model.message = acceptData[@"message"];
                                      model.image = @"denglushibai";
                                      model.title = @"登录失败";
                                      
                                      if (weakSelf.loginFieldBlock)
                                      {
                                          weakSelf.loginFieldBlock(model);
                                      }
                                                                          
                                      [weakSelf endEditing:YES];
                                  }
                                  else if(code.integerValue == 200)
                                  {
                                      [weakSelf sendMessageCutDown];
                                  }
                              }
                                fail:^(NSError * _Nullable error) {
                                    
                                }];
}

/**
 *  发送短信验证码
*/
- (void)sendMessageCutDown
{
    //倒计时时间 - 60秒
          __block NSInteger timeOut = 59;
          //执行队列
          dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
          //计时器 -》dispatch_source_set_timer自动生成
           _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
          dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
          dispatch_source_set_event_handler(_timer, ^{
              if (timeOut <= 0) {
                  dispatch_source_cancel(_timer);
                  //主线程设置按钮样式-》
                  dispatch_async(dispatch_get_main_queue(), ^{
                      [self.sendMessageButton setTitle:@"重新发送" forState:UIControlStateNormal];
                      [self.sendMessageButton setTitleColor:LCHexColor(0xFF7A17) forState:UIControlStateNormal];
                      [self.sendMessageButton.titleLabel setTextAlignment:NSTextAlignmentLeft];
                      [self.sendMessageButton setUserInteractionEnabled:YES];
                  });
              }else{
                  //开始计时
                  //剩余秒数 seconds
                  NSInteger seconds = timeOut % 60;
                  NSString *strTime = [NSString stringWithFormat:@"%.1ld",seconds];
                  //主线程设置按钮样式
                  dispatch_async(dispatch_get_main_queue(), ^{
                      [UIView beginAnimations:nil context:nil];
                      [UIView setAnimationDuration:1.0];
                      [self.sendMessageButton setTitle:[NSString stringWithFormat:@"%@s后重新发送",strTime] forState:UIControlStateNormal];
                      [self.sendMessageButton setTitleColor:LCHexColor(0x8B8B8B) forState:UIControlStateNormal];
                      self.sendMessageButton.titleLabel.adjustsFontSizeToFitWidth = YES;
                      [UIView commitAnimations];
                      //计时器件不允许点击
                      [self.sendMessageButton setUserInteractionEnabled:NO];
                  });
                  
                  timeOut--;
              }
          });
          
          dispatch_resume(_timer);
}

/**
 *  密码登录
*/
- (void)cipherLogin
{
     if (self.changeViewBlock)
     {
         self.changeViewBlock(self.phoneNum,self.codeTextFiedld.text);
     }
}
@end
